package com.ieng.kican.excption;

import com.ieng.kican.common.http.MR;
import com.ieng.kican.common.http.use.ActionR;
import com.ieng.kican.common.utils.IUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public MR<?> handleParameterVerifyException(Exception e) {
        String message = null;
        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getFieldError();
            if (IUtil.isNotObject(fieldError)) {
                message = fieldError.getDefaultMessage();
            }
        } else if (e instanceof MethodArgumentNotValidException) {
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            FieldError fieldError = result.getFieldError();
            if (IUtil.isNotObject(fieldError)) {
                message = fieldError.getDefaultMessage();
            }
        } else if (e instanceof ConstraintViolationException) {
            message = e.getMessage();
            if (IUtil.isNotObject(message) && message.lastIndexOf(":") > 0) {
                message = message.substring(message.lastIndexOf(":") + 1).trim();
            }
        } else {
            message = "请求参数异常";
        }

        return ActionR.error(message);
    }


}
